<template>
  <view class="admin-page">
    <view class="header">
      <text class="title">后台管理</text>
    </view>

    <view class="tabs">
      <view class="tab" :class="{ active: currentTab === 'stats' }" @click="currentTab = 'stats'">数据统计</view>
      <view class="tab" :class="{ active: currentTab === 'users' }" @click="currentTab = 'users'">用户管理</view>
      <view class="tab" :class="{ active: currentTab === 'settings' }" @click="currentTab = 'settings'">运营配置</view>
    </view>

    <view class="content">
      <!-- 数据统计 Tab -->
      <view v-if="currentTab === 'stats'" class="stats-container">
        <view class="stats-grid">
          <view class="stat-card">
            <view class="stat-icon">👥</view>
            <view class="stat-value">{{ stats.totalUsers || 0 }}</view>
            <view class="stat-label">总用户数</view>
          </view>
          <view class="stat-card">
            <view class="stat-icon">🆕</view>
            <view class="stat-value">{{ stats.todayUsers || 0 }}</view>
            <view class="stat-label">今日新增</view>
          </view>
          <view class="stat-card">
            <view class="stat-icon">💰</view>
            <view class="stat-value">{{ stats.pendingWithdrawals || 0 }}</view>
            <view class="stat-label">待处理提现</view>
          </view>
        </view>

        <view class="card" style="margin-top: 20rpx;">
          <text class="section-title">数据概览</text>
          <view class="data-row">
            <text class="data-label">总用户数：</text>
            <text class="data-value">{{ stats.totalUsers || 0 }} 人</text>
          </view>
          <view class="data-row">
            <text class="data-label">今日新增用户：</text>
            <text class="data-value">{{ stats.todayUsers || 0 }} 人</text>
          </view>
          <view class="data-row">
            <text class="data-label">待处理提现：</text>
            <text class="data-value">{{ stats.pendingWithdrawals || 0 }} 笔</text>
          </view>
        </view>
      </view>

      <!-- 用户管理 Tab -->
      <view v-if="currentTab === 'users'" class="users-container">
        <view class="card">
          <text class="section-title">用户列表</text>
          <view class="user-list">
            <view v-if="users.length === 0" class="empty-state">
              <text class="empty-icon">📋</text>
              <text class="empty-text">暂无用户数据</text>
            </view>
            <view v-for="user in users" :key="user._id" class="user-item">
              <view class="user-avatar">
                <image v-if="user.avatar_url" :src="user.avatar_url" mode="aspectFill" />
                <text v-else class="avatar-placeholder">👤</text>
              </view>
              <view class="user-info">
                <text class="user-name">{{ user.nickname || '未设置昵称' }}</text>
                <text class="user-detail">积分: {{ user.points || 0 }} | 等级: {{ user.level_name || '健康分享者' }}</text>
                <text class="user-detail">可提现: ¥{{ ((user.commission_available || 0) / 100).toFixed(2) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 运营配置 Tab -->
      <view v-if="currentTab === 'settings'" class="settings-container">
        <view class="card">
          <text class="section-title">分销规则设置</text>

          <view class="section-subtitle">积分规则</view>

          <view class="form-group">
            <view class="form-label">
              <text class="label-text">推荐新用户奖励</text>
              <text class="label-unit">(积分/人，10人封顶)</text>
            </view>
            <input
              class="form-input"
              type="number"
              v-model.number="rules.points.referralSuccess"
              placeholder="请输入积分数"
            />
            <text class="form-hint">当前设置：每推荐1个新用户获得 {{rules.points.referralSuccess || 0}} 积分，最多10人</text>
          </view>

          <view class="form-group">
            <view class="form-label">
              <text class="label-text">订单完成奖励</text>
              <text class="label-unit">(积分)</text>
            </view>
            <input
              class="form-input"
              type="number"
              v-model.number="rules.points.purchaseComplete"
              placeholder="请输入积分数"
            />
            <text class="form-hint">购买者和推广者在订单完成时各获得此积分</text>
          </view>

          <view class="section-subtitle">分级佣金规则</view>

          <view class="commission-levels-container">
            <view v-for="(level, index) in commissionLevels" :key="index" class="level-card">
              <view class="level-header">
                <text class="level-title">{{level.name}}</text>
                <text class="level-requirement">{{level.points_required}}分</text>
              </view>

              <view class="level-form">
                <view class="level-form-group">
                  <text class="level-label">等级名称</text>
                  <input
                    class="level-input"
                    type="text"
                    v-model="level.name"
                    placeholder="等级名称"
                  />
                </view>

                <view class="level-form-group">
                  <text class="level-label">积分要求</text>
                  <input
                    class="level-input"
                    type="number"
                    v-model.number="level.points_required"
                    placeholder="积分要求"
                  />
                </view>

                <view class="level-form-group">
                  <text class="level-label">佣金比例</text>
                  <view class="rate-input-group">
                    <input
                      class="level-input"
                      type="number"
                      step="1"
                      min="0"
                      max="100"
                      :value="getCommissionRatePercent(level)"
                      @input="updateCommissionRate(level, $event.target.value)"
                      placeholder="10"
                    />
                    <text class="rate-suffix">%</text>
                  </view>
                </view>
              </view>

              <text class="level-hint">
                {{level.name}}：积分≥{{level.points_required}}，佣金{{(level.commission_rate * 100).toFixed(1)}}%
              </text>
            </view>
          </view>

          <view class="form-group">
            <view class="form-label">
              <text class="label-text">返利激活时间</text>
              <text class="label-unit">(天)</text>
            </view>
            <input
              class="form-input"
              type="number"
              value="7"
              disabled
              style="background-color: #f5f5f5; color: #999;"
            />
            <text class="form-hint">订单完成后7天，返利自动转为可提现余额</text>
          </view>

          <button class="save-button" @click="saveRules">保存分销规则</button>
        </view>
      </view>

    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 'stats',
      stats: {
        totalUsers: 0,
        todayUsers: 0,
        pendingWithdrawals: 0
      },
      users: [],
      rules: {
        points: {
          newUserLogin: 0,
          referralSuccess: 0,
          purchaseComplete: 0
        },
        commission: {
          purchaseRebate: 0
        },
        commission_rules: {
          default_rate: 0.1,
          levels: [
            { name: '健康分享者', points_required: 0, commission_rate: 0.10 },
            { name: '推广大使', points_required: 101, commission_rate: 0.12 },
            { name: '区域代理', points_required: 501, commission_rate: 0.15 }
          ]
        }
      },
      // 分级佣金配置
      commissionLevels: [
        { name: '健康分享者', points_required: 0, commission_rate: 0.10 },
        { name: '推广大使', points_required: 101, commission_rate: 0.12 },
        { name: '区域代理', points_required: 501, commission_rate: 0.15 }
      ]
    };
  },
  computed: {
    commissionInYuan: {
      get() {
        return this.rules.commission.purchaseRebate / 100;
      },
      set(value) {
        this.rules.commission.purchaseRebate = Math.round(value * 100);
      }
    },
    commissionRatePercent: {
      get() {
        // purchaseRebate 是比例，例如 0.1 表示 10%
        return (this.rules.commission.purchaseRebate || 0) * 100;
      },
      set(value) {
        // 将百分比转换为小数，例如 10 转换为 0.1
        this.rules.commission.purchaseRebate = value / 100;
      }
    }
  },
  methods: {
    // 获取指定等级的佣金比例显示文本
    getLevelCommissionRate(level) {
      if (!level || !level.commission_rate) return '10%';
      return (level.commission_rate * 100).toFixed(1) + '%';
    },
    // 获取佣金比例的百分比数值（用于输入框显示）
    getCommissionRatePercent(level) {
      if (!level || !level.commission_rate) return 10;
      // 返回整数，避免小数位自动补充问题
      return Math.round(level.commission_rate * 100);
    },
    // 更新佣金比例（从百分比输入框）
    updateCommissionRate(level, percentValue) {
      const rate = parseFloat(percentValue);
      if (!isNaN(rate) && rate >= 0 && rate <= 100) {
        const newRate = rate / 100;
        // 使用Vue.set或强制更新来确保响应式
        this.$set(level, 'commission_rate', newRate);
      }
    },

    async fetchData(tab = this.currentTab) {
      uni.showLoading({ title: '加载中...' });
      try {
        let res;
        if (tab === 'stats') {
          // 获取统计数据
          res = await uniCloud.callFunction({
            name: 'admin-center',
            data: { action: 'getStats' }
          });
          if (res.result.code === 0) {
            this.stats = res.result.data;
          }
        } else if (tab === 'users') {
          // 获取用户列表
          res = await uniCloud.callFunction({
            name: 'admin-center',
            data: { action: 'getAllUsers' }
          });
          if (res.result.code === 0) {
            this.users = res.result.data || [];
          }
        } else if (tab === 'settings') {
          // 获取分销规则
          res = await uniCloud.callFunction({
            name: 'admin-center',
            data: { action: 'getRules' }
          });
          if (res.result.code === 0 && res.result.data) {
            // 兼容旧版本数据格式
            const rulesData = res.result.data;

            // 更新积分规则
            if (rulesData.points) {
              this.rules.points = {
                ...this.rules.points,
                ...rulesData.points
              };
            }

            // 兼容旧的佣金配置格式
            if (rulesData.commission) {
              this.rules.commission = {
                ...this.rules.commission,
                ...rulesData.commission
              };
            }

            // 新的分级佣金规则
            if (rulesData.commission_rules) {
              this.rules.commission_rules = {
                ...this.rules.commission_rules,
                ...rulesData.commission_rules
              };
              // 更新界面显示的分级配置
              if (rulesData.commission_rules.levels) {
                this.commissionLevels = [...rulesData.commission_rules.levels];
              }
            }
          }
        }

        if (res && res.result.code !== 0) {
          throw new Error(res.result.message);
        }
      } catch (error) {
        this.handleError(error);
      } finally {
        uni.hideLoading();
      }
    },

    async saveRules() {
      const confirmRes = await uni.showModal({
        title: '确认保存',
        content: '您确定要更新分销规则吗？此操作将影响未来的所有新交易。'
      });
      if (!confirmRes.confirm) return;

      // 验证佣金等级配置
      for (let i = 0; i < this.commissionLevels.length; i++) {
        const level = this.commissionLevels[i];
        if (!level.name || level.name.trim() === '') {
          uni.showToast({ title: `请填写等级${i + 1}的名称`, icon: 'none' });
          return;
        }
        if (level.points_required === null || level.points_required === undefined) {
          uni.showToast({ title: `请填写等级${i + 1}的积分要求`, icon: 'none' });
          return;
        }
        if (level.commission_rate === null || level.commission_rate === undefined) {
          uni.showToast({ title: `请填写等级${i + 1}的佣金比例`, icon: 'none' });
          return;
        }
        if (level.commission_rate < 0 || level.commission_rate > 1) {
          uni.showToast({ title: `等级${i + 1}的佣金比例必须在0%-100%之间`, icon: 'none' });
          return;
        }
      }

      // 最终确认提示
      const confirmText = `确认保存以下佣金规则吗？\n\n` +
        this.commissionLevels.map(level =>
          `${level.name}：${Math.round(level.commission_rate * 100)}%`
        ).join('\n');

      const finalConfirm = await uni.showModal({
        title: '最终确认',
        content: confirmText
      });

      if (!finalConfirm.confirm) return;


      uni.showLoading({ title: '保存中...' });
      try {
        // 更新佣金规则到最新的格式
        const rulesToSave = {
          ...this.rules,
          commission_rules: {
            default_rate: 0.1, // 默认等级佣金比例
            levels: [...this.commissionLevels]
          }
        };

        const res = await uniCloud.callFunction({
          name: 'admin-center',
          data: {
            action: 'updateRules',
            params: { rules: rulesToSave }
          }
        });
        if (res.result.code !== 0) {
          throw new Error(res.result.message);
        }
        uni.showToast({ title: '保存成功', icon: 'success' });
      } catch (error) {
        this.handleError(error);
      } finally {
        uni.hideLoading();
      }
    },

    handleError(error) {
      console.error('管理员页面错误:', error);
      uni.showToast({
        title: `错误: ${error.message}`,
        icon: 'none',
        duration: 3000
      });
      if (error.message.includes('权限')) {
        setTimeout(() => uni.navigateBack(), 2000);
      }
    }
  },
  onLoad() {
    this.fetchData();
  },
  watch: {
    currentTab(newTab) {
      this.fetchData(newTab);
    }
  }
};
</script>

<style scoped>
/* 页面基础样式 */
.admin-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #4a7c59 0%, #5a9d6a 100%);
  color: white;
  padding: 40rpx 30rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(74, 124, 89, 0.15);
}

.title {
  font-size: 40rpx;
  font-weight: bold;
}

/* Tab 标签样式 */
.tabs {
  display: flex;
  background-color: white;
  border-bottom: 1rpx solid #e5e5e5;
  position: sticky;
  top: 0;
  z-index: 100;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 30rpx 20rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.tab.active {
  color: #4a7c59;
  font-weight: bold;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #4a7c59;
  border-radius: 2rpx;
}

/* 内容区域 */
.content {
  padding: 20rpx;
}

.card {
  background-color: white;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.section-subtitle {
  font-size: 30rpx;
  font-weight: bold;
  color: #4a7c59;
  margin-top: 40rpx;
  margin-bottom: 30rpx;
  padding-left: 20rpx;
  border-left: 6rpx solid #4a7c59;
}

/* 数据统计样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.stat-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  text-align: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #f0f0f0;
}

.stat-icon {
  font-size: 48rpx;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #4a7c59;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

.data-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.data-row:last-child {
  border-bottom: none;
}

.data-label {
  font-size: 28rpx;
  color: #666;
}

.data-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

/* 用户列表样式 */
.user-list {
  margin-top: 20rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.user-item:last-child {
  border-bottom: none;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar image {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  font-size: 40rpx;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.user-detail {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

/* 表单样式 - 优化后 */
.form-group {
  margin-bottom: 40rpx;
}

.form-label {
  display: flex;
  align-items: baseline;
  margin-bottom: 16rpx;
}

.label-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.label-unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fafafa;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.form-input:focus {
  border-color: #4a7c59;
  background-color: white;
}

.form-hint {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
  padding-left: 12rpx;
  line-height: 1.6;
}

/* 保存按钮 */
.save-button {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4a7c59 0%, #5a9d6a 100%);
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 12rpx;
  margin-top: 40rpx;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(74, 124, 89, 0.3);
  transition: all 0.3s ease;
}

.save-button:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(74, 124, 89, 0.3);
}

/* 分级佣金样式 */
.commission-levels-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin: 20rpx 0;
}

.level-card {
  background: linear-gradient(135deg, #f8fdf8 0%, #ffffff 100%);
  border: 2rpx solid #e8f5e8;
  border-radius: 16rpx;
  padding: 25rpx;
  transition: all 0.3s ease;
}

.level-card:hover {
  box-shadow: 0 4rpx 16rpx rgba(74, 124, 89, 0.1);
  transform: translateY(-2rpx);
}

.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.level-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #4a7c59;
}

.level-requirement {
  font-size: 26rpx;
  color: #666;
  background-color: #f8f8f8;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.level-form {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  margin-bottom: 20rpx;
}

.level-form-group {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.level-label {
  font-size: 26rpx;
  color: #555;
  font-weight: 500;
}

.level-input {
  background-color: #f9f9f9;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 12rpx 16rpx;
  font-size: 28rpx;
  transition: border-color 0.3s ease;
}

.level-input:focus {
  border-color: #4a7c59;
  outline: none;
}

.rate-input-group {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.rate-suffix {
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
}

.level-hint {
  font-size: 24rpx;
  color: #888;
  background-color: #f8f8f8;
  padding: 10rpx 15rpx;
  border-radius: 8rpx;
  text-align: center;
}
</style>